﻿using DeHeng_Mes.Business;
using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.Data;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model;
using DeHeng_Mes.Utils;
using FluentFTP;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using FluentFTP.Helpers;
using yingli_ningbo.Helpers;
using MySqlX.XDevAPI;
using NPOI.SS.Formula.Functions;
namespace DeHeng_Mes.Mapper
{
    public class DataCollector
    {
        private readonly OrderDao orderDao = new OrderDao();
        private readonly ProcessDao processDao = new ProcessDao();
        private readonly DeviceDao deviceDao = new DeviceDao();
        private readonly ErrorStatusDao errorStatusDao = new ErrorStatusDao();

        /// <summary>
        /// 采集螺柱焊的生产数据。
        /// </summary>
        /// <param name="code">追溯码，用于唯一标识工件。</param>
        /// <param name="line">工序编号，用于区分不同的工序。</param>
        /// <param name="date">日期，用于定位相关数据文件。</param>
        /// <param name="dataPointer">数据指针，用于标识获取数据的起始位置。</param>
        /// <param name="batchSize">用于指定数据插入批次大小</param>
        /// <param name="orderCode">工单号</param>
        public void CollectDataForStudWelding(DateTime date, string orderCode, string code = "", string line = "", int dataPointer = 0, int batchSize = 0)
        {
            Tools.ProduceLogText("螺柱焊采集中...");
            string originPath = SystemConstant.swOriginPath;
            string savePath = SystemConstant.swSavePath;
            string suffix = SystemConstant.swSuffix;
            List<string> savedFiles = new List<string>();
            List<TraceStudWeld> traceStudWeldList = new List<TraceStudWeld>();


            SharedFolderAccess.CopyCsvFilesWithSuffixAndDeleteAsync(originPath, savePath, suffix);
            savedFiles = CsvUtils.FindCsvFiles(savePath);
            if (savedFiles == null || savedFiles.Count == 0)
            {
                Tools.ProduceLogText("未找到螺柱焊文件。");
                errorStatusDao.InsertSaveFailed(ProcessConstant.StudWelding, code);
            }
            else
            {
                foreach (var savedFile in savedFiles)
                {
                    try
                    {
                        // 假设你有一个名为 YourRecordType 的类来映射 CSV 文件的每一行
                        List<StudWeld> records = CsvUtils.ReadCsvFile<StudWeld>(savedFile, ";");
                        if (records != null && records.Count > 0)
                        {
                            foreach (var record in records)
                            {
                                if (record.traceNo == code)
                                {
                                    var traceStudWeld = new TraceStudWeld
                                    {
                                        TraceId = code,
                                        OrderCode = orderCode,
                                        WeldNo = record.weldNo,
                                        EquipmentNumber = record.equipmentNumber,
                                        Output = record.output,
                                        ProgramNumber = record.programNumber,
                                        WeldingTimeUpperLimit = record.weldingTimeUpperLimit,
                                        WeldingTimeLowerLimit = record.weldingTimeLowerLimit,
                                        WeldingTimeSetting = record.weldingTimeSetting,
                                        WeldingVoltageUpperLimit = record.weldingVoltageUpperLimit,
                                        WeldingVoltageLowerLimit = record.weldingVoltageLowerLimit,
                                        WeldingVoltageSetting = record.weldingVoltageSetting,
                                        ArcVoltageUpperLimit = record.arcVoltageUpperLimit,
                                        ArcVoltageLowerLimit = record.arcVoltageLowerLimit,
                                        ArcVoltageSetting = record.arcVoltageSetting,
                                        LiftingHeightUpperLimit = record.liftingHeightUpperLimit,
                                        LiftingHeightLowerLimit = record.liftingHeightLowerLimit,
                                        LiftingHeightSetting = record.liftingHeightSetting,
                                        MoltenPoolInsertionTimeUpperLimit = record.moltenPoolInsertionTimeUpperLimit,
                                        MoltenPoolInsertionTimeLowerLimit = record.moltenPoolInsertionTimeLowerLimit,
                                        MoltenPoolInsertionTimeSetting = record.moltenPoolInsertionTimeSetting,
                                        ImmersionPointUpperLimit = record.immersionPointUpperLimit,
                                        ImmersionPointLowerLimit = record.immersionPointLowerLimit,
                                        ImmersionPointSetting = record.immersionPointSetting,
                                        result = record.result,
                                    };
                                    var properties = typeof(TraceStudWeld).GetProperties();
                                    for (int i = 1; i <= 16; i++)
                                    {
                                        var currentProp = properties.FirstOrDefault(p => p.Name == $"Current{i}");
                                        var timeProp = properties.FirstOrDefault(p => p.Name == $"Time{i}");
                                        var pulsesProp = properties.FirstOrDefault(p => p.Name == $"NumberOfPulses{i}");

                                        if (currentProp != null) currentProp.SetValue(traceStudWeld, record.GetType().GetProperty($"current{i}").GetValue(record));
                                        if (timeProp != null) timeProp.SetValue(traceStudWeld, record.GetType().GetProperty($"time{i}").GetValue(record));
                                        if (pulsesProp != null) pulsesProp.SetValue(traceStudWeld, record.GetType().GetProperty($"numberOfPulses{i}").GetValue(record));
                                    }

                                    traceStudWeldList.Add(traceStudWeld);
                                }
                            }
                            if (traceStudWeldList.Count > 0)
                            {
                                try
                                {
                                    processDao.InsertStudWeldData(traceStudWeldList);
                                }
                                catch (Exception ex)
                                {
                                    Tools.ProduceLogTextError($"处理螺柱焊文件 {savedFile} 时发生错误: {ex.Message}");
                                    errorStatusDao.InsertSaveFailed(ProcessConstant.StudWelding, code);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.ProduceLogTextError($"处理螺柱焊文件 {savedFile} 时发生错误: {ex.Message}");
                        errorStatusDao.InsertSaveFailed(ProcessConstant.StudWelding, code);
                    }
                }
            }
        }

        /// <summary>
        /// 采集除胶视觉的生产数据。
        /// </summary>
        /// <param name="code">追溯码，用于唯一标识工件。</param>
        /// <param name="process">生产线编号，用于区分左、右生产线。</param>
        /// <param name="date">日期，用于定位相关数据文件。</param>
        /// <param name="dataPointer">数据指针，可能用于标识数据的具体位置（尚未使用）。</param>
        /// <param name="batchSize">用于指定数据插入批次大小</param>
        /// <param name="orderCode">订单号</param>
        public void CollectDataForGlueRemovalVision(DateTime date, string orderCode, string code = "", string process = "", int dataPointer = 0, int batchSize = 0)
        {
            string path = string.Empty;

            // 根据线体获取文件路径
            if (process == "")
            {
                errorStatusDao.InsertSaveFailed(ProcessConstant.GlueRemoval, code, process);
            }

            if (process.Contains("L"))
            {
                path = SystemConstant.LeftGlueRemovalPath;
            }
            else if (process.Contains("R"))
            {
                path = SystemConstant.RightGlueRemovalPath;
            }

            // 补全路径并添加日期
            string day = date.ToString("yyyy-MM-dd");
            path = System.IO.Path.Combine(path, day);
            try
            {
                // 查找包含二维码的 Json 文件
                List<string> list = FindJsonFilesWithSubstring(path, code);
                if (list != null && list.Count > 0)
                {
                    try
                    {
                        // 获取 Json 内容并反序列化
                        string jsonContent = File.ReadAllText(list[0]);
                        GlueRemovalVision data = JsonSerializer.Deserialize<GlueRemovalVision>(jsonContent);

                        foreach (var visionData in data.RoiData)
                        {
                            var newTraceGlueRemoval = new TraceGlueRemoval
                            {
                                TraceId = code,
                                OrderCode = orderCode,
                                RobotId = data.layer,
                                Operation = process,
                                PointName = visionData.Key,
                                Result = visionData.Value.ToString()
                            };
                            processDao.InsertGlueRemovalVisionData(newTraceGlueRemoval);
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.ProduceLogTextError($"除胶视觉解析或插入 Json 文件 {list[0]} 的数据时出现错误: {ex.Message}");
                        if (list.Count == 1)
                        {
                            errorStatusDao.InsertSaveFailed(ProcessConstant.GlueRemoval, code, process);
                        }

                    }
                }
                else
                {
                    // 未找到当前 Code 的相关数据，递归查找前一天的数据，最多递归 8 天
                    DateTime previousDay = date.AddDays(-1);
                    if ((DateTime.Now - previousDay).TotalDays <= SystemConstant.day)
                    {
                        // 递归调用，但返回递归结果
                        CollectDataForGlueRemovalVision(previousDay, orderCode, code, process, dataPointer, batchSize);
                    }
                    else
                    {
                        // 记录未找到数据的日志
                        Tools.ProduceLogText($"除胶视觉轮询线程中未找到 {SystemConstant.day} 天内追溯码为 {code} 的相关数据");
                        errorStatusDao.InsertSaveFailed(ProcessConstant.GlueRemoval, code, process);
                    }
                }

            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"除胶视觉轮询线程中出现错误: {ex.Message}");
                errorStatusDao.InsertSaveFailed(ProcessConstant.GlueRemoval, code, process);
            }
        }

        /// <summary>
        /// 采集涂胶的生产数据。
        /// </summary>
        /// <param name="code">追溯码，用于唯一标识工件。</param>
        /// <param name="line">生产线编号，用于区分左、右及小工位。</param>
        /// <param name="date">日期，用于定位相关数据文件。</param>
        /// <param name="dataPointer">数据指针，可能用于标识数据的具体位置（尚未使用）。</param>
        /// <param name="batchSize"></param>
        /// <param name="orderCode">订单号</param>
        public void CollectDataForGluing(DateTime date, string orderCode, string code = "", string line = "", int dataPointer = 0, int BatchSize = 0)
        {
            FtpClient client = new FtpClient();

            FtpHelper ftpHelper;

            try
            {
                if (line == "")
                {
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                    return;
                }
                string loadPath = string.Empty;
                string copyPath = string.Empty;
                string station = string.Empty;
                FtpListItem[] items;
                TimeSpan generatedTime = deviceDao.getTimeByTraceCode(code);

                if (line.Contains("Op30Fixed"))
                {
                    copyPath = SystemConstant.leftGlueCopyPath;
                    loadPath = SystemConstant.leftGlueLoadPath;
                    station = "left";
                    ftpHelper = new FtpHelper(client, "192.168.10.100", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }
                else if (line.Contains("Op60Fixed"))
                {
                    copyPath = SystemConstant.rightGlueCopyPath;
                    loadPath = SystemConstant.rightGlueLoadPath;
                    station = "right";
                    ftpHelper = new FtpHelper(client, "192.168.10.101", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }
                else if (line.Contains("Op90Fixed"))
                {
                    copyPath = SystemConstant.rightGlueCopyPath;
                    loadPath = SystemConstant.rightGlueLoadPath;
                    station = "right";
                    ftpHelper = new FtpHelper(client, "192.168.10.102", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }
                else if (line.Contains("Op10"))
                {
                    copyPath = SystemConstant.rightGlueCopyPath;
                    loadPath = SystemConstant.rightGlueLoadPath;
                    station = "right";
                    ftpHelper = new FtpHelper(client, "192.168.11.100", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }
                else
                {
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                    return;
                }
                Tools.ProduceLogText("涂胶采集中...");
                // 获取根目录下的文件和文件夹列表
                string operateTime = date.ToString("yyyy-MM-dd");
                string todayString = DateTime.Now.ToString("yyyy-MM-dd");

                if (!operateTime.Equals(todayString))
                {
                    todayString = operateTime;
                }

                // 筛选包含指定字段的文件
                var matchingFileList = items
                    .Where(item => item.Type == FtpObjectType.File && item.Name.Contains(todayString))
                    .ToList();
                if (matchingFileList.Count > 0)
                {
                    // 检查本地路径是否存在，如果不存在则创建
                    if (!Directory.Exists(copyPath))
                    {
                        Directory.CreateDirectory(copyPath);
                    }
                    foreach (var file in matchingFileList)
                    {
                        string localFilePath = Path.Combine(copyPath, file.Name);
                        // 下载文件到本地
                        var status = client.DownloadFile(localFilePath, file.FullName, FtpLocalExists.Overwrite, FtpVerify.Retry);
                        if (status == FtpStatus.Success)
                        {
                            Tools.DeviceLogText($"下载涂胶CSV文件 {file.Name} 成功,完整文件路径为：{localFilePath}。");
                            List<Glue> records = CsvUtils.ReadCsvFile<Glue>(localFilePath, ",", false);
                            if (records != null && records.Count > 0)
                            {
                                Glue record = records.Last(); // 或 records[records.Count - 1];
                                string defaultTime = "1900-01-01 00:00:00";
                                var traceGlue = new TraceGlue
                                {
                                    TraceId = code,
                                    OrderCode = orderCode,
                                    OperationId = station,
                                    CoatingSpeed = (record.CostTime.HasValue && record.GlueFlowRate.HasValue && record.CostTime.Value != 0) ? ((record.GlueFlowRate.Value / record.CostTime.Value)).ToString() : "N/A",
                                    CoatingFlowRate = record.GlueFlowRate.ToString(),
                                    CoatingPressure = (record.MinPressure.HasValue && record.MaxPressure.HasValue) ? ((record.MinPressure + record.MaxPressure) / 2).ToString() : "N/A",
                                    CoatingTemperature = record.GlueGunTemperature.ToString(),
                                    CoatingTime = record.CostTime.ToString(),
                                    StartTime = DateTime.ParseExact($"{record.Date.ToString("yyyy-MM-dd")} {record.SystemStartTime}", "yyyy-MM-dd HHmmss", null),
                                    EndTime = (record.SystemEndTime.Equals("0"))
                                    ? DateTime.Parse(defaultTime)
                                    : DateTime.ParseExact($"{record.Date.ToString("yyyy-MM-dd")} {record.SystemEndTime}", "yyyy-MM-dd HHmmss", null)
                                };
                                try
                                {
                                    processDao.InsertGlueData(traceGlue);
                                    errorStatusDao.DeleteSaveFailed(ProcessConstant.Glue, code, line);

                                }
                                catch (Exception ex)
                                {
                                    Tools.ProduceLogTextError($"处理涂胶文件 {localFilePath} 时发生错误: {ex.Message}");
                                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                                }
                            }
                            else
                            {
                                Tools.DeviceLogText($"下载涂胶文件 {file.Name} 失败: {file.FullName},服务器为{client.Host}");
                                errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                            }
                        }
                        else
                        {
                            Tools.DeviceLogText($"下载涂胶文件 {file.Name} 失败: {file.FullName},服务器为{client.Host}");
                            errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                        }
                    }
                    Tools.ProduceLogText("涂胶采集结束");
                }
                else
                {
                    Tools.ProduceLogTextError($"服务器为{client.Host}读取涂胶CSV文件失败：未生成文件");
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"服务器为{client.Host}读取涂胶CSV文件失败：" + ex.Message);
                errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
            }
            finally
            {
                // 确保无论发生什么情况都能断开连接
                if (client.IsConnected)
                {
                    client.Disconnect();
                }
            }
        }

        /// <summary>
        /// 采集点焊数据并插入数据库。
        /// 该方法读取 CSV 文件，根据追溯码匹配记录，生成点焊追溯数据并存储到数据库。
        /// </summary>
        /// <param name="code">追溯码，用于匹配记录。</param>
        /// <param name="operation">产线编号（未使用）。</param>
        /// <param name="date">指定的日期，用于构造文件路径。</param>
        /// <param name="dataPointer">数据指针（未使用）。</param>
        /// <param name="orderCode">订单号</param>
        public void CollectDataForSpotWelding(DateTime date, string orderCode, string code = "", string operation = "", int dataPointer = 0, int BatchSize = 0)
        {
            try
            {
                Tools.ProduceLogText("点焊采集中...");
                string path = SystemConstant.SpotWeldingPath;
                var robots = MappingTable.GetRobotByOperation(operation);
                string day = date.ToString("yyyyMMdd");
                List<string> codeList = new List<string>();
                List<TraceSpotWeld> dataList = new List<TraceSpotWeld>();
                int saveCount = 0;

                /*                if (Directory.Exists(networkPath))
                                {
                                    Console.WriteLine("共享文件夹存在，文件列表如下：");
                                }*/

                foreach (var robot in robots)
                {
                    string contentDictionary = "DATA" + robot;
                    string totalPath = Path.Combine(path, contentDictionary) + "\\" + day + ".csv";
                    try
                    {
                        List<SpotWeld> records = CsvUtils.ReadCsvFile<SpotWeld>(totalPath);
                        if (MappingTable.MapRobot(robot))
                        {
                            codeList = processDao.GetSpotWeldTraceCodeDeep(code);
                            foreach (var splitCode in codeList)
                            {
                                try
                                {
                                    if (records != null && records.Count > 0)
                                    {
                                        foreach (var record in records)
                                        {
                                            if (record.TraceCode == splitCode)
                                            {
                                                TraceSpotWeld spotWeld = new TraceSpotWeld
                                                {
                                                    TraceId = record.TraceCode,
                                                    RobotId = record.RobotId,
                                                    OrderCode = orderCode,
                                                    WeldNo = record.SpotNo,
                                                    WeldingProgramNumber = record.SpecificationNo,
                                                    WeldingTime1 = record.SpotTime1,
                                                    WeldingCurrent1 = record.SpotCurrent1,
                                                    WeldingTime2 = record.SpotTime2,
                                                    WeldingCurrent2 = record.SpotCurrent2,
                                                    WeldingTime3 = record.SpotTime3,
                                                    WeldingCurrent3 = record.SpotCurrent3,
                                                    DotCount = record.MoldRepairCount,
                                                    WeldingResistance = record.SpotResistance,
                                                    WeldingSpatter = record.IsFlying,
                                                    WeldingSpatterOccurrenceTime = record.FlyingTime,
                                                    WeldingCurrentUpperLimit = record.CurrentUpperLimit,
                                                    WeldingCurrentLowerLimit = record.CurrentLowerLimit,
                                                    WeldingEnergyUpperLimit = record.PowerUpperLimit,
                                                    WeldingEnergyLowerLimit = record.PowerLowerLimit,
                                                    WeldingResistanceUpperLimit = record.ResistanceUpperLimit,
                                                    WeldingResistanceLowerLimit = record.ResistanceLowerLimit,
                                                    NumberOfWelds = saveCount.ToString(),
                                                    StepIncrementSectionNumber = record.StepCount
                                                };
                                                dataList.Add(spotWeld);
                                            }

                                        }
                                        saveCount += 1;
                                    }
                                    else
                                    {
                                        Tools.ProduceLogText($"点焊追溯码为{code}未生成数据");
                                        errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                                        return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Tools.ProduceLogTextError($"点焊数据解析或插入数据库时出现错误: {ex.Message},追溯码为{code}");
                                    errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                                    return;
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                if (records != null && records.Count > 0)
                                {
                                    foreach (var record in records)
                                    {
                                        if (record.TraceCode == code)
                                        {
                                            TraceSpotWeld spotWeld = new TraceSpotWeld
                                            {
                                                TraceId = record.TraceCode,
                                                OrderCode = orderCode,
                                                RobotId = record.RobotId,
                                                WeldNo = record.SpotNo,
                                                WeldingProgramNumber = record.SpecificationNo,
                                                WeldingTime1 = record.SpotTime1,
                                                WeldingCurrent1 = record.SpotCurrent1,
                                                WeldingTime2 = record.SpotTime2,
                                                WeldingCurrent2 = record.SpotCurrent2,
                                                WeldingTime3 = record.SpotTime3,
                                                WeldingCurrent3 = record.SpotCurrent3,
                                                DotCount = record.MoldRepairCount,
                                                WeldingResistance = record.SpotResistance,
                                                WeldingSpatter = record.IsFlying,
                                                WeldingSpatterOccurrenceTime = record.FlyingTime,
                                                WeldingCurrentUpperLimit = record.CurrentUpperLimit,
                                                WeldingCurrentLowerLimit = record.CurrentLowerLimit,
                                                WeldingEnergyUpperLimit = record.PowerUpperLimit,
                                                WeldingEnergyLowerLimit = record.PowerLowerLimit,
                                                WeldingResistanceUpperLimit = record.ResistanceUpperLimit,
                                                WeldingResistanceLowerLimit = record.ResistanceLowerLimit,
                                                NumberOfWelds = saveCount.ToString(),
                                                StepIncrementSectionNumber = record.StepCount
                                            };
                                            dataList.Add(spotWeld);
                                        }

                                    }
                                    saveCount += 1;
                                }
                                else
                                {
                                    Tools.ProduceLogText($"点焊追溯码为{code}未生成数据");
                                    errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                Tools.ProduceLogTextError($"点焊数据解析或插入数据库时出现错误: {ex.Message},追溯码为{code}");
                                errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.ProduceLogText($"点焊追溯码为{code}未生成数据: {ex.Message}");
                        errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                        return;
                    }
                }
                try
                {
                    if (saveCount >= 1 && saveCount <= 2 && saveCount == robots.Count && dataList.Count > 0)
                    {
                        processDao.InsertSpotWeldData(dataList);
                        Tools.ProduceLogText($"点焊数据插入数据库成功，追溯码为{code}");
                    }
                    else
                    {
                        Tools.ProduceLogText($"点焊追溯码为{code}未生成数据");
                        errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"点焊数据插入数据库时出现错误: {ex.Message}");
                    errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"点焊数采出现错误: {ex.Message}");
                errorStatusDao.InsertSaveFailed(ProcessConstant.SpotWelding, code, operation);
            }
        }
        #region 内部方法

        /// <summary>
        /// 根据目标字符串在根路径及其子文件夹中搜索包含目标字符串的 JSON 文件路径。
        /// </summary>
        /// <param name="rootPath">根目录路径。</param>
        /// <param name="targetString">目标字符串，用于匹配文件夹或文件名。</param>
        /// <returns>返回包含目标字符串的 JSON 文件的完整路径列表。</returns>
        List<string> FindJsonFilesWithSubstring(string rootPath, string targetString)
        {
            List<string> jsonFiles = new List<string>();

            try
            {
                // 获取当前路径下的所有文件夹
                foreach (string dir in Directory.GetDirectories(rootPath))
                {
                    // 检查文件夹名称是否包含目标字符串
                    if (dir.Contains(targetString))
                    {
                        // 查找文件夹内包含目标字符串的 JSON 文件
                        foreach (string file in Directory.GetFiles(dir, "*.json"))
                        {
                            if (file.Contains(targetString))
                            {
                                jsonFiles.Add(file);  // 添加完整路径
                            }
                        }
                    }
                    // 递归搜索子文件夹
                    jsonFiles.AddRange(FindJsonFilesWithSubstring(dir, targetString));
                }
            }
            catch (UnauthorizedAccessException) // 处理权限不足的异常
            {
                Tools.ProduceLogTextError("没有权限访问路径：" + rootPath);
            }
            return jsonFiles;
        }
        #endregion
    }
}
